# -*- coding: utf-8 -*-

import _thread
import hashlib
import json
import time

import requests

"""

吖咪接口测试代码  多个主播开播
Created on Tue Jul 27 12:41:39 2021

@author: Administrator
"""


def getHtml(url, paramss, phone, type="post"):
    try:
        path = phone + ".txt"
        file = open(path, "r")
        fileData = file.read()
        token = ""
        yzt = ""
        try:
            json_to_python = json.loads(fileData)
            token = json_to_python['Data']["token"]
            cell = json_to_python['Data']["cell"]
            pwd = json_to_python['Data']["password"]
            yzt = getUrlYzt(cell, pwd)
        except Exception as e1:
            print("===json 解析出错:" + str(e1))
        file.close()
        header = {'Content-Type': 'application/json; charset=UTF-8',
                  "app_type": "1",
                  "version": "1.21.38-test210617-1",
                  "Authorization": token}
        if ("post" == type):
            url += yzt
            print("================  请求地址和参数  ======================")
            print(url)
            print(paramss)
            print("========================================================")
            data = requests.post(url, data=paramss, headers=header, timeout=2)
        else:
            data = requests.get(url, data=paramss, headers=header, timeout=2)
        data.encoding = "utf-8"
        # print(data.text)
        return data.text
    except Exception as e:
        print(str(e))
        return "异常"


# 有的接口需要yzt参数
def getYzt(mydata):
    mydata = mydata + "a4be9f32637e217fb8dbbcae75759fb3"
    return hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()


# Url参数添加验证码
def getUrlYzt(account, password):
    cdt = str(round(time.time() * 1000))
    mydata = account + password + cdt
    yzt = hashlib.md5(mydata.encode(encoding='UTF-8')).hexdigest()
    s_act = account + "_" + password + "_" + yzt
    return "?act=" + s_act + "&cdt=" + cdt


# 登录之后获取用户id
def getUid(phone):
    file = open(phone + ".txt", "r")
    fileData = file.read()
    try:
        json_to_python = json.loads(fileData)
        file.close()
        return json_to_python['Data']["uid"]
    except Exception:
        file.close()
        return ""


"""
==============================================================================
    实际用户API接口调用
==============================================================================
"""


# 登录将登录数据放在文件中
def login(phone, code="831246"):  # 831246 202088
    # phone = "18782927715"
    # paramss =  '{"uid":"40026", "amount":"9800"}'
    paramss = {"code": code, "cell": phone, "did": "imei866182040064619",
               "mac": "3C:86:D1:5A:EB:13", "dev": "", "plat": "vivo_V1928A", "ver": "28_9",
               "sys": "androidphone", "sver": "1.21.39-test210726_18", "firm": "9",
               "mart": "android", "token": "", "ip": "192.168.0.201", "source": "and-0",
               "yzt": getYzt(phone), "lat": "30.554378",
               "lng": "104.07132", "city": "510100", "cityname": "成都市",
               "state": "510000", "statename": "四川省"}

    dd = str(paramss)
    # print(dd)
    par = dd.encode("utf-8").decode("latin-1")
    data = getHtml(URLHOST + "yonghu/celllogin", par, phone)
    print(data)
    file = open(phone + ".txt", "w")
    file.write(data)
    file.close()


def 直播间签到奖励领取(type, phone):  # type = "s" 签到  “d” 红人
    paramss = {"uid": getUid(phone), "utype": "1", "type": type}
    text = URLHOST + "yonghu/receiverank"
    print(getHtml(text, json.dumps(paramss), phone))


# 实名认证
def 开始直播(phone):
    # {lat=30.554227, lng=104.071163, state=510000, statename=四川省, city=510100, cityname=成都市, uid=40076, labelid=1, room_type=1}
    paramss = {"uid": getUid(phone), "lat": "30.554227", "lng": "104.071163", "state": "510000", "statename": "四川省",
               "city": "510100", "cityname": "成都市", "labelid": "1", "room_type": "1"}
    text = URLHOST + "zhibo/createchatroom"
    # data_gb2312 = unquote(paramss, encoding='utf-8')
    response = getHtml(text, json.dumps(paramss), phone)
    print(response)


# =====================================直播心跳任务
def 直播心跳任务(phone):
    paramss = {"uid": getUid(phone), "key": getUid(phone)}
    text = URLHOST + "zhibo/chargingroom"
    response = getHtml(text, json.dumps(paramss), phone)
    try:
        json_to_python = json.loads(response)
        print("直播同步时间：: " + str(json_to_python["IsError"]) + "  ----  " + str(json_to_python["ErrorMessage"]))
        if 1 == json_to_python["IsError"]:
            开始直播(phone)
    except Exception as e1:
        print("直播同步时间error ：" + str(e1))


# ======================================直播心跳任务循环
def 直播心跳任务循环(val, phone):
    try:
        print(val)
        for i in range(1, 1000):
            time.sleep(20)
            直播心跳任务(phone)
    except Exception as e1:
        print("Error: 循环错误" + str(e1))


# ======================================测试线程


def 开播心跳同步():
    for item in userList:
        开始直播(item)
        直播间签到奖励领取("s", item)
        直播间签到奖励领取("d", item)
    # 创建两个线程
    try:
        for item in userList:
            time.sleep(1)
            _thread.start_new_thread(直播心跳任务循环, ("开始执行任务Thread-" + item, item,))
    except:
        print("Error: 无法启动线程")

    while 1:
        pass


# 测试环境
URLHOST = "http://apitest.yamizhibo.com/api/"
ALLCODE = 202088  # 831246
userList = ["13540124221", "18782927715", "17190085924", "13540124222", "13540124223", "13540124224", "13540124225",
            "13540124226",
            "13540124227", "13540124228", "13540124229", "13540124230", "13540124231", "13540124232", "13540124233",
            "13540124234", "13540124235"]
# =====================================================================================================================
# main 主函数
# =====================================================================================================================
if __name__ == '__main__':
    # for item in userList:
    #     login(item, ALLCODE)

    # 需要先登录才能执行下面的操作
    开播心跳同步()

    while 1:
        pass
